# -*- coding:utf-8 -*-
from database.db_business import DbBusiness
from common.my_time import MyTime
from common.my_baidu import MyBaidu
from common.market_data import MarketData
from bs4 import BeautifulSoup
import glob
import jieba
import re
import threading
import hashlib
import urllib.parse
import time
import os

'''
网络数据
'''

#file = open('./out/' + os.path.split(__file__)[-1].split(".")[0], 'w', encoding = 'utf-8')

class Dazongshangpin:
    def __init__(self):
        self.market = MarketData()
        self.business = DbBusiness()

    def check_site(self, site_name):
        site_lists = ["新浪","东方财富网","同花顺","每日经济新闻","和讯","第一财经","证券时报","经济观察报","中国财经信息网"]
        for d in site_lists:
            if re.search(d, site_name):
                return True
        print(site_name)
        return False
    
    def get_data(self, word):
        datas = self.business.query_dazongshangpin()
        end_date = MyTime.forward_relative_date(3)
        check_title = [word]
        for k in datas:
            next_page = True
            words = [k, word]
            for i in range(1,3):
                if next_page == False:
                    break
                url = MyBaidu.get_url_order_by_time(words, i)
                try:
                    proxy = self.business.query_proxy()
                    res = MyBaidu.get_baidu_data_by_proxy(url, proxy)
                    for r in res:
                        data_date = MyBaidu.calc_date(r["date"])
                        if data_date < end_date:
                            next_page = False
                            break
                        if self.check_site(r["site"]) == False:
                            continue
                        if MyBaidu.check_title(r["title"], [[k], check_title]) == False:
                            continue
                        data_title = r["title"]
                        data_site = r["site"]
                        data_url = r["url"]
                        print(r["date"] + data_date)
                        self.market.add_market_data(data_date, 2100, data_title, data_url, data_site)
                except Exception as e:
                    #i = i - 1
                    pass

def dazongshangpin_api():
    d = Dazongshangpin()
    d.get_data("库存")
    d.get_data("合约")
    d.get_data("期货")
    d.get_data("现货")
    d.get_data("原材料")


if __name__ == '__main__':
    dazongshangpin_api()

